
App({
    api: {
        getOpenId: require('./config').getOpenId,
        uploadFileUrl: require('./config').uploadFileUrl,
        findSubjectQuestionsNumber: require('./config').findSubjectQuestionsNumber,
        findStudentByOpenId: require('./config').findStudentByOpenId,
        goodsListUrl: require('./config').goodsListUrl,
        findQuestionsNumber: require('./config').findQuestionsNumber,
        listSchool: require('./config').listSchool,
        listGrade: require('./config').listGrade,
        saveStudent: require('./config').saveStudent,
        updateStudent: require('./config').updateStudent,
        // 订单
        reserveOrder: require('./config').reserveOrder,
        toPayOrderSuccess: require('./config').toPayOrderSuccess,
        findOwnOrders: require('./config').findOwnOrders,
        findOwnOrderById: require('./config').findOwnOrderById,
        // 预支付
        prePay: require('./config').prePay,
    },
    url: {
        pay: '/pages/homework/pages/pay/pay',
    },
    status: {
        isLoading: false,
    },
    globalData: {
        userInfo: null,
        hasLogin: false,

        // appid: 'wx62194e92c186b153',
        // secret: '888ea3215b80f892fbeb6d835d0e7934',
        appid: 'wx2aab06d693cd499c',
        secret: 'e72c527c07e479ce505cb716f60645c0',

        openId: null,
        studentInfo: null,
        hasReg: false,
        
        index_url : '/pages/index/index',
        reg_url : '/pages/userinfo/index',
        showPopup: 1,
    },
    onLaunch: function() {
        var that = this;
        // that.getRegData();
        // 登录
        // var self = this;
        // wx.login({
        //     success: function(data) {
        //         wx.request({
        //             url: 'https://api.weixin.qq.com/sns/jscode2session?appid='+self.globalData.appid+'&secret='+self.globalData.secret+'&js_code='+data.code+'&grant_type=authorization_code',
        //             data: {},
        //             success: function(res) {
        //                 console.log('拉取openId成功', res.data.openId);
        //                 self.globalData.openId = res.data.openId;
        //                 if (this.userInfoReadyCallback) {
        //                     this.userInfoReadyCallback(res)
        //                 }
        //             },
        //             fail: function(res) {
        //                 console.log('拉取用户openId失败，将无法正常使用开放接口等服务', res);
        //             }
        //         })
        //     },
        //     fail: function(err) {
        //         console.log('wx.login 接口调用失败，将无法正常使用开放接口等服务', err);
        //     }
        // })
        // 获取用户信息
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            this.globalData.userInfo = res.userInfo

                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            // 所以此处加入 callback 以防止这种情况
                            if (this.userInfoReadyCallback) {
                                this.userInfoReadyCallback(res)
                            }
                        }
                    })
                }
            }
        });     
        that.getStudentInfo();
    },
    getStudentInfo: function(needUpdate, callback) {
        var that = this;
        that.getUseropenId(function(openId) {
            // console.log(openId);
            that.globalData.openId = openId;
            that.findStudentByOpenId(openId, needUpdate, function(data) {
                that.globalData.hasReg = true;
                that.globalData.studentInfo = {
                    // id: data.id,
                    name: data.name,
                    parentName: data.parentName,
                    phone: data.phone,
                    email: data.email,
                    sex: data.sex,
                    schoolId: data.schoolId,
                    gradeId: data.gradeId,
                    classId: data.classId,
                };
                callback && callback();
                // console.log(that.globalData.hasReg);
                // console.log(that.globalData.studentInfo);
            })
        });
    },
    findStudentByOpenId: function(openId, needUpdate,  callback) {
        var self = this;
        needUpdate = needUpdate || 0;
        if (!needUpdate && self.globalData.studentInfo) {
            callback && callback(self.globalData.studentInfo);
        } else {
            wx.request({
                url: self.api.findStudentByOpenId + openId  + '?time=' + Date.parse(new Date()),
                data: {},
                header: { 'Content-Type': 'application/json' },
                method: 'POST',
                success: function(rs) {                    
                    if (rs.data.status == '0') {
                        console.log('该用户已注册');
                        callback && callback(rs.data.data);
                    } else {
                        console.log('该用户未注册');
                    }
                }
            });
        }
    },
    getUseropenId: function(callback) { 
        var self = this;
        if (self.globalData.openId) {
            callback && callback(self.globalData.openId);
        } else {
            wx.login({
                success: function(data) {
                    console.log(data.code);
                    wx.request({
                        url: self.api.getOpenId+'?code=' + data.code,
                        data: {},
                        success: function(res) {
                            // console.log('拉取openId成功', res.data.openid);   
                            if(!res.data) {                     
                                wx.showModal({
                                    title: '拉取openId失败',
                                    content: 'openId:'+ res.data,
                                });
                                return false;
                            }                       
                            // wx.showModal({
                            //     title: '拉取openId成功',
                            //     content: 'openId:'+ res.data.openid,
                            // })  
                            //alert(res.data.openid)
                            //self.globalData.openId = res.data.openid;
                            callback && callback(res.data.openid);
                        },
                        fail: function(res) {                            
                            // wx.showModal({
                            //     title: '拉取openId失败',
                            //     content: 'error:'+res,
                            // })  
                            console.log('拉取用户openId失败，将无法正常使用开放接口等服务', res)
                            //callback && callback(null);
                        }
                    })
                },
                fail: function(err) {
                    console.log('wx.login 接口调用失败，将无法正常使用开放接口等服务', err)
                    callback && callback(null);
                }
            })
        }
    },
    showLoading: function(set_status, time) {
        if(set_status) this.status.isLoading = true;
        wx.showToast({
          title: "loading",
          icon: "loading",
          duration: time || 10000
        });
    },
    hideLoading: function(set_status, time) {
        var self = this;
        setTimeout(function(){
            if(set_status) self.status.isLoading = false;
            wx.hideToast();
        },time || 0);
    }
})